package com.example.keli.ui.area;

import android.Manifest;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.keli.R;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.app.C;
import com.example.keli.base.utils.LocationManager;
import com.example.keli.base.widget.BladeView;
import com.example.keli.base.widget.PinnedHeaderListView;
import com.flyco.roundview.RoundTextView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class AreaActivity extends BaseActivity {


    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
//    @BindView(R.id.flowlayout_hot)
//    TagFlowLayout flowlayoutHot;
    private List<AreaVO> mHotList = new ArrayList<>();
    @BindView(R.id.listview)
    PinnedHeaderListView listview;
    @BindView(R.id.bladeview)
    BladeView bladeview;
    List<AreaVO> childrens = new ArrayList<>();
    List<AreaVO> sortChildrens = new ArrayList<>();

    // 首字母集
    private List<String> mSections;
    // 根据首字母存放数据
    private Map<String, List<String>> mMap = new HashMap<>();
    // 首字母位置集
    private List<Integer> mPositions = new ArrayList<>();
    // 首字母对应的位置
    private Map<String, Integer> mIndexer = new HashMap<>();

    AreaAdapter addressAdapter;
    String[] sortList = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};

    @Override
    protected int layoutId() {
        return R.layout.activity_area;
    }

    @Override
    protected void bindData() {
        abTitle.setText("选择地区");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initArea();
    }

    private void initArea() {
//        mAreaVOS = new ArrayList<>();
//        String city_name = SPUtils.get(this, C.SP.AREA_CITY, "全国站");
        AreaVO areaVO = new AreaVO();
        areaVO.setId(39);
        areaVO.setPid(37);
        areaVO.setName("济南市");
        mHotList.add(areaVO);
        View view = LayoutInflater.from(AreaActivity.this).inflate(R.layout.header_area, listview, false);
        listview.addHeaderView(view);
        TagFlowLayout flowlayoutHot = view.findViewById(R.id.flowlayout_hot);
        LinearLayout ll_location = view.findViewById(R.id.ll_location);
        RoundTextView all_city = view.findViewById(R.id.all_city);
        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                EventBus.getDefault().post(new LocationVO());
//                finish();
                getPermissions();
            }
        });
        all_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AreaVO areaVO = new AreaVO();
                areaVO.setId(371);
                areaVO.setPid(371);
                areaVO.setName("全国");
                EventBus.getDefault().post(areaVO);
                finish();
            }
        });
        setAdapter(flowlayoutHot);
        tvCity.setText(C.CURRENT_CITY_NAME);
        loadDatas();
    }

        private void getPermissions() {
        requestPermission(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, "需要定位权限，是否允许使用位置权限", new GrantedResult() {
            @Override
            public void onResult(boolean granted) {
                if (granted){
                    //同意定位
                    startProgressDialog();
                    LocationManager.getInstance().initLocation(AreaActivity.this, new LocationManager.LocationCall() {
                        @Override
                        public void suc(AreaVO areaVO) {
                            //定位完成，包含成功和失败，根据city是否为空判断。
                            stopProgressDialog();
                            finish();
                        }
                    });
                }else {
                    toast("需要定位权限，无法定位");
                    AreaVO areaVO = new AreaVO();
                    areaVO.setId(-1);
                    areaVO.setPid(-1);
                    areaVO.setName("定位失败");
                    EventBus.getDefault().post(areaVO);
                    finish();
                }
            }
        });
    }

    private void loadDatas() {
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.getActivityRegion(), new SubscriberListener<BaseResponse<List<AreaVO>>>() {
            @Override
            public void onSuccess(BaseResponse<List<AreaVO>> listBaseResponse) {
                List<AreaVO> addressDatas = listBaseResponse.getData();
                childrens.addAll(addressDatas);

                dealData();
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    private static final String FORMAT = "^[A-Z].*$";

    private void dealData() {
        for (int i = 0; i < sortList.length; i++) {
            for (int j = 0; j < childrens.size(); j++) {
                String firstName = childrens.get(j).getPinyin();
                if (sortList[i].contains(firstName)) {
                    sortChildrens.add(childrens.get(j));
                }
            }
        }
        mSections = new ArrayList<>();
        mMap = new HashMap<>();
        mPositions = new ArrayList<>();
        mIndexer = new HashMap<>();

        if (sortChildrens != null && sortChildrens.size() > 0) {
            for (int i = 0; i < sortChildrens.size(); i++) {
                String firstName = sortChildrens.get(i).getPinyin();

                if (firstName.matches(FORMAT) || firstName.contains("#")) {
                    if (mSections.contains(firstName)) {
                        mMap.get(firstName).add(sortChildrens.get(i).getPinyin());
                    } else {
                        mSections.add(firstName);
                        List<String> list = new ArrayList<String>();
                        list.add(sortChildrens.get(i).toString());
                        mMap.put(firstName, list);
                    }
                }
            }
            int position = 0;
            for (int i = 0; i < mSections.size(); i++) {
                mIndexer.put(mSections.get(i), position);// 存入map中，key为首字母字符串，value为首字母在listview中位置
                mPositions.add(position);// 首字母在listview中位置，存入list中
                position += mMap.get(mSections.get(i)).size();// 计算下一个首字母在listview的位置
            }
        }


        bladeview.setOnItemClickListener(new BladeView.OnItemClickListener() {
            public void onItemClick(String s) {
                if (mIndexer.get(s) != null) {
                    listview.setSelection(mIndexer.get(s));
                }
            }
        });
        addressAdapter = new AreaAdapter(AreaActivity.this, sortChildrens, mSections, mPositions);
        listview.setAdapter(addressAdapter);
        listview.setOnScrollListener(addressAdapter);
        View view = LayoutInflater.from(AreaActivity.this).inflate(R.layout.view_find_brand, listview, false);
        listview.setPinnedHeaderView(view);
        addressAdapter.setCallBack(new SelectCall() {
            @Override
            public void selectCall(AreaVO areaVO) {
                if (areaVO != null) {
                    //SPUtils.put(AreaActivity.this, C.SP.AREA_CITY, city_name);
                    C.CURRENT_CITY_NAME = areaVO.getName();
                    EventBus.getDefault().post(areaVO);
                }
                finish();
            }
        });
    }

//    @OnClick(R.id.ll_location)
//    public void onViewClicked() {
//
//    }

    public interface SelectCall {
        void selectCall(AreaVO areaVO);
    }

    private void setAdapter(final TagFlowLayout tagFlowLayout) {
        final TagAdapter<AreaVO> tagAdapter = new TagAdapter<AreaVO>(mHotList) {
            @Override
            public View getView(FlowLayout parent, int position, AreaVO areaVO) {
                TextView tag = (TextView) LayoutInflater.from(AreaActivity.this).inflate(R.layout.tag_area, tagFlowLayout, false);
                tag.setText(areaVO.getName());
                return tag;
            }
        };
        tagFlowLayout.setAdapter(tagAdapter);
        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                AreaVO areaVO = tagAdapter.getItem(position);
                if (areaVO != null) {
                    //SPUtils.put(AreaActivity.this, C.SP.AREA_CITY, city_name);
                    C.CURRENT_CITY_NAME = areaVO.getName();
                    EventBus.getDefault().post(areaVO);
                }
                finish();
                return false;
            }
        });
    }

}
